package com.itheima.service.impl;

import com.itheima.anno.Log;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    //删除部门（同时删除该部门下的员工）
    //默认情况下，只有出现RuntimeException(运行时异常)才会回滚事务。
    //rollbackFor这个属性可以指定出现何种异常类型回滚事务。
    @Override
    @Log
    @Transactional(rollbackFor = Exception.class)  //spring事物管理
    public void delete(Integer id) throws Exception {
        try {
            deptMapper.deleteById(id); //根据ID删除部门数据
            //模拟：异常发生
//            if(true){
//                throw new Exception("出现异常了~~~");
//            }
            empMapper.deleteByDeptId(id);  //根据部门ID删除该部门下的员工
        } finally {
            //不论是否有异常，最终都要执行
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此时解散的是"+id+"号部门");
            //调用其他业务类中的方法
            deptLogService.insert(deptLog);
        }
    }

    @Override
    @Log
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }




    //修改部门(先查再改)
    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectById(id);
    }
    @Override
    @Log
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }



}
